﻿package com.firewolf.swing.tree.UI;

import java.awt.Color;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.plaf.basic.BasicTreeUI;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;

public class FriendsTree extends JFrame {
	private static final long serialVersionUID = 2729875043188879933L;
	private final int LOCATION_X = 200;
	private final int LOCATION_Y = 200;
	private final int WIDTH = 300;
	private final int HEIGHT = 500;

	public FriendsTree() {
		setBounds(LOCATION_X, LOCATION_Y, WIDTH, HEIGHT);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JScrollPane jscrollpanel = new JScrollPane();
		jscrollpanel.setViewportView(getJTree());
		add(jscrollpanel);
	}

	private JTree getJTree() {
		String[][] students = new String[][]{
				{"唐僧","孙悟空","猪八戒","沙和尚"},
				{"冷血","追命","铁手"},
				{"老虎","狮子","大猩猩","猴子","犀牛"}
		};
		JTree tree = new JTree();
		DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode();
		// 创建根节点的对象
//		rootNode.setUserObject("同学录");
		// 创建根节点下的分组节点
		for (int i = 0; i < students.length; i++) {
			DefaultMutableTreeNode teamNode = new DefaultMutableTreeNode();
			teamNode.setUserObject("第" + (i+1) + "组好友");
			for (int j = 0; j < students[i].length; j++) {
				DefaultMutableTreeNode leafNode = new DefaultMutableTreeNode();
				leafNode.setUserObject(students[i][j]);
				teamNode.add(leafNode);

			}
			rootNode.add(teamNode);
		}
		// 设定默认的树结构模式
		DefaultTreeModel model = new DefaultTreeModel(rootNode);
		tree.setModel(model);
//		tree.setRootVisible(false);
//		tree.setShowsRootHandles(true);
		ImageIcon icon = new ImageIcon("src\\images\\leaf.png");
//		ImageIcon hebing = new ImageIcon("src\\images\\hebing.png");
//		ImageIcon zhankai = new ImageIcon("src\\images\\zhankai.png");
		ImageIcon collapsedIcon = new ImageIcon("src\\images\\hebing.png");
		ImageIcon expandedIcon = new ImageIcon("src\\images\\zhankai.png");
		DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
		// 设定叶节点的图标
		renderer.setLeafIcon(icon);
		
//		// 设定分组被收起后的图标
		renderer.setClosedIcon(null);
		// 设定分组展开时的图标
		renderer.setOpenIcon(null);
		// 设定被选项的边缘框的颜色
		renderer.setBorderSelectionColor(Color.red);
		// 将renderer对象对JTree所做的各种修饰效果添加到界面
		tree.setCellRenderer(renderer);
		BasicTreeUI treeUI = (BasicTreeUI) tree.getUI();
		treeUI.setCollapsedIcon(collapsedIcon);
		treeUI.setExpandedIcon(expandedIcon);
		return tree;
	}
}
